package com.aliyun.oss.UserService.impl;

import com.aliyun.oss.UserMapper.OrdersMapper;
import com.aliyun.oss.UserService.*;
import com.aliyun.oss.pojo.DTO.OrdersPaymentDTO;
import com.aliyun.oss.pojo.DTO.OrdersSubmitDTO;
import com.aliyun.oss.pojo.Entity.Orders;
import com.aliyun.oss.pojo.Entity.ShoppingCart;
import com.aliyun.oss.pojo.Entity.WxUser;
import com.aliyun.oss.pojo.Entity.addressBook;
import com.aliyun.oss.pojo.Vo.AllOrdersVO;
import com.aliyun.oss.pojo.Vo.OrderPaymentVO;
import com.aliyun.oss.pojo.Vo.OrderSubmitVO;
import com.aliyun.oss.utils.GetNowTime;
import com.aliyun.oss.websocket.WebSocketServer;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
    @Autowired
    AddressBookService addressBookService;
    @Autowired
    ShoppingCartService shoppingCartService;

    @Autowired
    OrderDetailService orderDetailService;
    @Autowired
    WxUserService wxUserService;
    @Autowired
    WebSocketServer webSocketServer;

    @Override
    public OrderSubmitVO submitOrder(Integer id, OrdersSubmitDTO ordersSubmitDTO) {
//        1.处理各种业务异常（地址为空，购物车数据为空）
        addressBook byId = addressBookService.getById(ordersSubmitDTO.getAddressBookId());
        if (byId == null) {
            throw new RuntimeException("地址为空");
        }
        List<ShoppingCart> list = shoppingCartService.list(id);
        if (list == null || list.size() == 0) {
            throw new RuntimeException("购物车数据为空");
        }
//        2.插入订单数据
        Orders orders = new Orders();
//        将ordersSubmitDTO的值复制给orders对象
        orders.setUserId(id);
        orders.setAddressBookId(ordersSubmitDTO.getAddressBookId().intValue());
        orders.setPayMethod(ordersSubmitDTO.getPayMethod());
        orders.setRemark(ordersSubmitDTO.getRemark());
        orders.setEstimatedDeliveryTime(ordersSubmitDTO.getEstimatedDeliveryTime());
        orders.setDeliveryStatus(ordersSubmitDTO.getDeliveryStatus());
        orders.setTablewareNumber(ordersSubmitDTO.getTablewareNumber());
        orders.setTablewareStatus(ordersSubmitDTO.getTablewareStatus());
        orders.setPackAmount(ordersSubmitDTO.getPackAmount());
        orders.setAmount(ordersSubmitDTO.getAmount());
        orders.setOrderTime(GetNowTime.getNowTime());
        orders.setPayStatus(orders.UN_PAID);
        orders.setStatus(orders.PENDING_PAYMENT);
        orders.setNumber("2025" + System.currentTimeMillis());
        orders.setPhone(byId.getPhone());
        orders.setAddress(byId.getProvinceName() + byId.getCityName() + byId.getDistrictName() + byId.getDetail());
        orders.setConsignee(byId.getConsignee());
//        插入数据
        save(orders);

//        3.插入n条订单明细
        orderDetailService.insertBatch(orders.getId(), list);
//        4.清空该用户的购物车
        shoppingCartService.remove(new QueryWrapper<ShoppingCart>().eq("user_id", id));
//        5.封装VO返回数据
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO(orders.getId(), orders.getNumber(), orders.getAmount(), orders.getOrderTime());
        return orderSubmitVO;
    }

    @Override
    public OrderPaymentVO payment(Integer id, OrdersPaymentDTO ordersPaymentDTO) {
//        根据id查询用户
//        WxUser wxUser = wxUserService.getById(id);
//        是这样的，订单支付功能，暂时不写，因为没有微信支付的商户号
        String orderNumber = ordersPaymentDTO.getOrderNumber();
        Orders one = getOne(new QueryWrapper<Orders>().eq("number", orderNumber).eq("user_id", id));
        if (one != null) {
            one.setStatus(Orders.TO_BE_CONFIRMED);
            one.setPayStatus(Orders.PAID);
            updateById(one);
        }
//        使用websocket发送消息给所有用户 type=1 orderId content
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("type", 1);
        hashMap.put("orderId", one.getId());
        hashMap.put("content","订单号:"+one.getNumber());
//        map转 json
        // 创建ObjectMapper实例
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            // 将Map转换为JSON字符串
            String jsonString = objectMapper.writeValueAsString(hashMap);
            webSocketServer.sendMessage(jsonString);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void processTimeoutOrder() {
//        查询订单状态为待支付状态，而且订单创建时间为当前时间-15分钟前的订单
        List<Orders> list = list(new QueryWrapper<Orders>().eq("status", Orders.PENDING_PAYMENT).lt("order_time", LocalDateTime.now().minusMinutes(15)));
        for (Orders orders : list) {
//            将订单状态改为6
            orders.setStatus(Orders.CANCELLED);
            orders.setCancelReason("支付超时");
            orders.setCancelTime(LocalDateTime.now());
            updateById(orders);
        }
    }

    @Override
    public void processDeliveryOrder() {
        List<Orders> list = list(new QueryWrapper<Orders>().eq("status", Orders.DELIVERY_IN_PROGRESS).lt("order_time", LocalDateTime.now().minusMinutes(60)));
        for (Orders orders : list) {
//            将订单状态改为5
            orders.setStatus(Orders.COMPLETED);
            updateById(orders);
        }

    }

    @Override
    public List<AllOrdersVO> getAllOrders(Integer id) {
        List<AllOrdersVO> allOrdersVOList= baseMapper.getAllOrders(id);
        return allOrdersVOList;
    }
}
